//
//  HomeViewController.m
//  XieZB
//
//  Created by Sam on 16/10/24.
//  Copyright © 2016年 XieZB. All rights reserved.
//

#import "HomeViewController.h"
#import "WXApiRequestHandler.h"
#import "WXApiManager.h"
#import "QMCameraViewController.h"

@interface HomeViewController ()<UIWebViewDelegate,UIActionSheetDelegate>

@property (nonatomic, strong) UIWebView *webview;
@property (nonatomic, assign) BOOL isJump;
@property (nonatomic, strong) NSURLRequest *request;
@property (nonatomic, strong) NSArray *shareArray;
@property (nonatomic, strong) UIView *statusBarView;

@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    //[self setBarView];
    self.webview = [[UIWebView alloc] init];
  
    self.webview.delegate = self;
    self.webview.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.webview];
    
    
    self.request = [NSURLRequest requestWithURL:[NSURL URLWithString:BaseWeb] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0];
    [self.webview loadRequest:self.request];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(uploadSuccess) name:@"UploadSuccess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wechatLogin) name:@"GetCodeSuccess" object:nil];
}


- (void)wechatLogin{
    NSString *code = [[NSUserDefaults standardUserDefaults] objectForKey:@"code"];
    NSString *url = [NSString stringWithFormat:@"http://pigai.hexinedu.com/mobile/#/login?code=%@",code];
    self.request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0];
    [self.webview loadRequest:self.request];
}


- (void)viewDidLayoutSubviews {
    self.webview.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
}

- (void)setStatusBarBackgroundColor:(UIColor *)color {
    
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    
    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
        statusBar.backgroundColor = color;
    }
}

- (void)uploadSuccess{
    
    [self.webview stringByEvaluatingJavaScriptFromString:@"PiGaiAPP.goBackAfterTakePicture()"];
    
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    NSLog(@"%@",request.URL.absoluteString);
    if([request.URL.absoluteString isEqualToString:@"http://pigai.hexinedu.com/mobile/#/login"]){
        [self setStatusBarBackgroundColor:[UIColor whiteColor]];
    }else{
        [self setStatusBarBackgroundColor:[UIColor colorWithHexString:kMainColor]];
    }
    
    if ([request.URL.absoluteString hasPrefix:@"pigaiapp://"]){
        
        NSString *url = request.URL.absoluteString;
        NSString *action, *type;
        if([url hasPrefix:@"pigaiapp://upload/multi"]){
            action = @"upload";
            type = @"multi";
            NSArray *array = [url componentsSeparatedByString:@"?"];
            NSString *sep = @"=&";
            NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:sep];
            NSArray *temp = [[array objectAtIndex:1] componentsSeparatedByCharactersInSet:set];
            if(temp.count == 2){
            
                QMCameraViewController *vc = [[QMCameraViewController alloc] init];
                vc.selectType = type;
                vc.exerciseUid = [temp objectAtIndex:1];
                [self presentViewController:vc animated:YES completion:nil];
                return NO;
            }else{
                [self.view showError:@"schema参数错误"];
                return NO;
            }

            
        }else if([url hasPrefix:@"pigaiapp://upload/single"]){
            action = @"upload";
            type = @"single";
            NSArray *array = [url componentsSeparatedByString:@"?"];
            NSString *sep = @"=&";
            NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:sep];
            NSArray *temp = [[array objectAtIndex:1] componentsSeparatedByCharactersInSet:set];
            if(temp.count == 4){
                QMCameraViewController *vc = [[QMCameraViewController alloc] init];
                vc.selectType = type;
                vc.exerciseUid = [temp objectAtIndex:1];
                vc.studentUid = [temp objectAtIndex:3];
                [self presentViewController:vc animated:YES completion:nil];
                return NO;
            }else{
                [self.view showError:@"schema参数错误"];
                return NO;
            }

            
            
        }else if([url hasPrefix:@"pigaiapp://share"]){
            
            NSArray *array = [url componentsSeparatedByString:@"?"];
            NSString *sep = @"=&";
            NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:sep];
            NSArray *temp = [[array objectAtIndex:1] componentsSeparatedByCharactersInSet:set];
            if(temp.count == 6){
                self.shareArray = @[[temp objectAtIndex:1],[temp objectAtIndex:3],[temp objectAtIndex:5]];
                UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"分享给好友",@"分享到朋友圈", nil];
                [sheet showInView:self.view];
            }else{
                [self.view showError:@"schema参数错误"];
            }
            
            return NO;
            
        }else if([url hasPrefix:@"pigaiapp://wechat"]){
            
            SendAuthReq *request = [[SendAuthReq alloc] init];
            request.scope = @"snsapi_userinfo";
            request.state = @"xiezuobao";
            [WXApi sendReq:request];
            
            
            
        }

    }
    
    
    return YES;
}

- (void)actionSheet:(UIActionSheet *)actionSheet willDismissWithButtonIndex:(NSInteger)buttonIndex {
    
    NSString *title =  [[self.shareArray objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *desc = [[self.shareArray objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *url = [[self.shareArray objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    switch (buttonIndex) {
        case 0: {
            //分享给好友

            [WXApiRequestHandler sendLinkURL:url
                                     TagName:nil
                                       Title:title
                                 Description:desc
                                  ThumbImage:nil
                                     InScene:WXSceneSession];
            break;
        }
        case 1: {
            //分享到朋友圈
            [WXApiRequestHandler sendLinkURL:url
                                     TagName:nil
                                       Title:title
                                 Description:desc
                                  ThumbImage:nil
                                     InScene:WXSceneTimeline];
            break;
        }
    }
    actionSheet = nil;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    
    NSHTTPCookie *cookie;
    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (cookie in [cookieJar cookies]) {
        NSLog(@"%@", cookie);
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
    [self setStatusBarBackgroundColor:[UIColor whiteColor]];
    if(![self.request.URL.absoluteString isEqualToString:@"http://pigai.hexinedu.com/mobile/#/login"]){
        [self setStatusBarBackgroundColor:[UIColor colorWithHexString:kMainColor]];
    }
}
@end
